package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.dto.*;
import com.zb.entity.TbAlarmModel;
import com.zb.influx.InfluxReposityory;
import com.zb.mapper.TbAlarmMapper;
import com.zb.service.TbAlarmService;
import com.zb.util.Pager;
import joptsimple.internal.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @ClassName TbAlarmServiceImpl
 * @Description 服务接口实现
 * @Author xm
 * @Date 2025/03/26 11:23
 **/
@Service
public class TbAlarmServiceImpl extends ServiceImpl<TbAlarmMapper, TbAlarmModel>implements TbAlarmService {

    @Override
    public TbAlarmModel verifyQuota(QuotaDTO quotaDTO) {
        //根据指标编号查询报警列表
        LambdaQueryWrapper<TbAlarmModel> qw = new LambdaQueryWrapper<>();
        qw.eq(TbAlarmModel::getQuotaId,quotaDTO.getId());
        List<TbAlarmModel> alarmModelList = list(qw);
        TbAlarmModel alarmModel = null;
        for (TbAlarmModel tbAlarmModel : alarmModelList) {
            //验证操作符和指标对比
            //验证字符串的报警数据，字符串和boolean报警数据只能是=
            if ("String".equals(quotaDTO.getValueType())
                || "Boolean".equals(quotaDTO.getValueType())) {
                if (tbAlarmModel.getOperator().equals("=")
                        && quotaDTO.getStringValue().equals(tbAlarmModel.getThreshold().toString())){
                    alarmModel = tbAlarmModel;
                    break;
                }
            }else{
                if (tbAlarmModel.getOperator().equals(">")
                        && quotaDTO.getValue()>tbAlarmModel.getThreshold()){
                    alarmModel = tbAlarmModel;
                    break;
                } else if (tbAlarmModel.getOperator().equals("<")
                        && quotaDTO.getValue()<tbAlarmModel.getThreshold()) {
                    alarmModel = tbAlarmModel;
                    break;
                }else if (tbAlarmModel.getOperator().equals("=")
                        && quotaDTO.getValue().equals(tbAlarmModel.getThreshold())) {
                    alarmModel = tbAlarmModel;
                    break;
                }
            }
        }
        return alarmModel;
    }

    @Override
    public DeviceInfoDTO verifyDeviceInfo(DeviceInfoDTO deviceInfoDTO) {
        //初始化设备 默认为没有报警
        DeviceDTO device = deviceInfoDTO.getDevice();
        device.setAlarm(false);
        device.setAlarmName("正常");
        device.setLevel(0);
        device.setOnline(true);
        device.setStatus(true);
        //获取解析后的指标数据，并验证指标数据是否报警
        List<QuotaDTO> quotaList = deviceInfoDTO.getQuotaList();
        for (QuotaDTO quotaDTO : quotaList) {
            //调用验证每一个指标的方法，并获取是否报警的数据
            TbAlarmModel alarmModel = this.verifyQuota(quotaDTO);
            if (alarmModel!=null){
                quotaDTO.setAlarm("1");
                quotaDTO.setAlarmName(alarmModel.getName());
                quotaDTO.setLevel(alarmModel.getLevel().toString());
                quotaDTO.setAlarmWebhook(alarmModel.getWebhook());
                quotaDTO.setCycle(alarmModel.getCycle());
                //设备报警等级升级
                if (alarmModel.getLevel() > device.getLevel()){
                    device.setAlarm(true);
                    device.setAlarmName(alarmModel.getName());
                    device.setLevel(alarmModel.getLevel());
                }
            }else {
                //当前指标没有报警,报警数据初始化为正常
                quotaDTO.setAlarm("0");
                quotaDTO.setAlarmName("正常");
                quotaDTO.setLevel("0");
                quotaDTO.setAlarmWebhook("");
                quotaDTO.setCycle(0);
            }
        }
        return deviceInfoDTO;
    }

    @Autowired
    private InfluxReposityory influxReposityory;
    @Override
    public Pager<QuotaAllInfo> queryAlarmToInflux(Long page, Long pageSize, String start, String end, String alarmName, String deviceId) {

        StringBuffer whereQl = new StringBuffer("where alarm = '1'");
        if (!Strings.isNullOrEmpty(start)){
            whereQl.append("and time >='"+start+"'");
        }
        if (!Strings.isNullOrEmpty(end)){
            whereQl.append("and time <='"+end+"'");
        }
        if (!Strings.isNullOrEmpty(alarmName)){
            whereQl.append("and alarmName =~/"+alarmName+"/");
        }
        if (!Strings.isNullOrEmpty(deviceId)){
            whereQl.append("and deviceId =~/^"+deviceId+"/");
        }
        StringBuffer listQl = new StringBuffer("select * from quota ");
        listQl.append(whereQl.toString());
        listQl.append("order by desc limit "+pageSize+" offset "+(page-1)*pageSize);
        System.out.println(listQl.toString());

        List<QuotaAllInfo> quotaAllInfoList = influxReposityory.query(listQl.toString(), QuotaAllInfo.class);
        //处理日期类型转换成格式化之后的日期
        for (QuotaAllInfo quotaAllInfo : quotaAllInfoList) {
            LocalDateTime parse = LocalDateTime.parse(quotaAllInfo.getTime(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            String format = parse.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            quotaAllInfo.setTime(format);
        }
        StringBuffer countQl = new StringBuffer("select count(value) from quota ");
        countQl.append(whereQl.toString());
        System.out.println(countQl.toString());
        List<QuotaCount> quotaCounts = influxReposityory.query(countQl.toString(), QuotaCount.class);
        Pager<QuotaAllInfo> pager = new Pager<>();
        pager.setIndex(page.intValue());
        pager.setSize(pageSize.intValue());
        pager.setData(quotaAllInfoList);
        pager.setCount(quotaCounts.get(0).getCount().intValue());
        return pager;

    }
}
